<?php
/**
 * Created by Business.php.
 * User: wy
 * Date: 2019/5/13
 * Time: 10:56
 */

namespace app\admin\controller;
use my\Tools;
use think\Db;
use app\admin\model\RegionModel;
use my\Security;
class Business extends Base
{
    public function index(){
        $page = input('get.page');
        $limit = input('get.limit');
        $map = ['is_del'=>1];
        if ($page && $limit) {
            if(input('get.name')){
                $name = input('get.name');
                $map['name'] =  ['like',"%$name%"];
            }
            if(input('get.province_id')){
                $map['province_id'] = input('get.province_id');
            }
            if(input('get.city_id')){
                $map['city_id'] = input('get.city_id');
            }

            if(input('get.country_id')){
                $map['country_id'] = input('get.country_id');
            }
            $start = ($page - 1) * $limit;
            $count = Db::name('business')->where($map)->count();
            $list = Db::name('business')->field('id,name,reg_num,first_num,username,phone,qr_code,province_id,city_id,country_id')->where($map)->limit($start, $limit)->order('id desc')->select();
            foreach ($list as $key=>$value){
                $list[$key]['province_name']    = Db::name('region')->where('region_id',$value['province_id'])->value('region_name');
                $list[$key]['city_name']        = Db::name('region')->where('region_id',$value['city_id'])->value('region_name');
                $list[$key]['country_name']     = Db::name('region')->where('region_id',$value['country_id'])->value('region_name');
            }
;            return json([
                'code' => 0,
                'msg' => '',
                'limit' =>$limit,
                'count' => $count,
                'data' => $list
            ]);
        }
        //查询省市区
        $region_model = new RegionModel();
        //查询获取省份
        $where = [
            'parent_id'     => 1,
            'region_level'  => 1
        ];
        $config['province'] = $region_model->getRegion($where,'region_id,region_name');
        $this->assign($config);
        return $this->fetch();
    }

    public function excel(){
        $type = input('get.type');
        $page = input('get.page') ?: 1;
        $limit = $type == 1 ? 1000 : input('get.limit');
        $start = ($page - 1) * $limit;
        $header = json_decode(input('get.headers'));
        $map = ['is_del'=>1];
        //****搜索功能
        if(input('get.name')){
            $name = input('get.name');
            $map['name'] =  ['like',"%$name%"];
        }
        if(input('get.province_id')){
            $map['province_id'] = input('get.province_id');
        }
        if(input('get.city_id')){
            $map['city_id'] = input('get.city_id');
        }
        if(input('get.country_id')){
            $map['country_id'] = input('get.country_id');
        }
        $list = Db::name('business')->field('id,name,reg_num,first_num,username,phone,qr_code,province_id,city_id,country_id')->where($map)->limit($start, $limit)->order('id desc')->select();
        foreach ($list as $key=>$value){
            $list[$key]['province_name']    = Db::name('region')->where('region_id',$value['province_id'])->value('region_name');
            $list[$key]['city_name']        = Db::name('region')->where('region_id',$value['city_id'])->value('region_name');
            $list[$key]['country_name']     = Db::name('region')->where('region_id',$value['country_id'])->value('region_name');
        }
        if(empty($list)){
            return "<script>alert('暂无数据');parent.window.location.reload()</script>";
        }
        foreach ($list as $key => $value) {
            foreach ($header as $k => $v) {
                $data[$key][$v] = $value[$k];
            }
        }
        Tools::excelExport('车队信息', $header, $data);
    }

    //生成二维码
    public function refer_code(){
        $id = input('get.id');
        //验证推广员信息是否存在
        $referInfo = DB::name('business')->where(['id'=>$id])->find();
        if(empty($referInfo)){
            $this->error('不存在车队信息', '', '', 1);
        }
        //判断文件二维码是否存在
        if( @fopen( $referInfo['qr_code'], 'r' ) ){
            $this->assign('referInfo',$referInfo);
        }else{
//            $content = \think\Env::get('url'.ENV.'_hdache').'/business.html?id='.$referInfo['id'];
//            $content = 'http://devm.xiaomachuxing.com/business.html?uid='.$referInfo['id'].'&invitetype=5'; //测试地址
//            $content = \think\Env::get('url'.ENV.'_url').'/business.html?uid='.$referInfo['id'].'&invitetype=5';  //正式地址
            $content = 'http://m.xiaomachuxing.cn/business.html?uid='.$referInfo['id'].'&invitetype=5';  //正式地址
            $path = ROOT_PATH.'/tmp/';
            $file = $referInfo['id'].'.png';
            $file_name = 'code_url';
            $result = Tools::makeQRCode($content,$path.'.'.$file,$file_name,'L','6',$referInfo['id']);
            if($result['status'] == 1){
                Db::name('business')->where('id',$id)->update(['qr_code'=>$result['qr_code']]);
            }else{
                $this->error('生成二维码失败', '', '', 1);
            }
            $this->assign('referInfo',$result);
        }
        return $this->fetch();
    }

    //新增车队
    public function add(){
        if(input('post.')){
            $data = input('post.');
            $map['name'] = $data['name'];
            $map['city_id'] = $data['city_id'];
            $info = Db::name('business')->where($map)->find();
            if(!empty($info)){
                $this->error('对不起该车队名称已存在', '', '', 1);
            }
            Db::name('business')->insertGetId($data);
            return "<script type='application/javascript'>parent.window.location.reload();</script>";
        }
        //查询省市区
        $region_model = new RegionModel();
        //查询获取省份
        $where = [
            'parent_id'     => 1,
            'region_level'  => 1
        ];
        $provinceList = $region_model->getRegion($where,'region_id,region_name');
        $this->assign('provinceList',$provinceList);
        return $this->fetch();
    }

    //修改
    public function edit(){
        if(input('post.')){
            if(input('post.id')){
                $data = input('post.');
                $map['name'] = $data['name'];
                $map['city_id'] = $data['city_id'];
                $map['id'] = ['<>',$data['id']];
                $info = Db::name('business')->where($map)->find();
                if(!empty($info)){
                    $this->error('对不起该车队名称已存在', '', '', 1);
                }
                $result = Db::name('business')->update($data);
                if($result){
                    return "<script type='application/javascript'>alert('修改成功');parent.window.location.reload();</script>";
                }
            }
        }elseif(input('get.id')){
            $id = input('get.id');
            $data = Db::name('business a')
                ->field('a.*,b.region_name region_name_province,c.region_name region_name_city,d.region_name region_name_country')
                ->join('region b','a.province_id=b.region_id','LEFT')
                ->join('region c','a.city_id=c.region_id','LEFT')
                ->join('region d','a.country_id=d.region_id','LEFT')
                ->where('id',$id)->find();
            $this->assign('data',$data);
            //查询省市区
            $region_model = new RegionModel();
            //查询获取省份
            $where = [
                'parent_id'     => 1,
                'region_level'  => 1
            ];
            $provinceList = $region_model->getRegion($where,'region_id,region_name');
            $this->assign('provinceList',$provinceList);
            //查询获取市
            unset($where);
            $where = [
                'parent_id'     => $data['province_id'],
                'region_level'  => 2
            ];
            $cityList = $region_model->getRegion($where,'region_id,region_name');
            $this->assign('cityList',$cityList);
            //查询获取区
            unset($where);
            $where = [
                'parent_id'     =>  $data['city_id'],
                'region_level'  => 3
            ];
            $countryList = $region_model->getRegion($where,'region_id,region_name');
            $this->assign('countryList',$countryList);
            return $this->fetch();
        }else{
            $this->error('无效的ID', '', '', 1);
        }
    }

    //删除
    public function del(){
        if(input('get.id')){
            $id = input('get.id');
            $data = Db::name('business')->where('id',$id)->update(['is_del'=>2]);
            if($data){
                exit(json_encode(['status'=>1,'msg'=>'删除成功']));
            }else{
                exit(json_encode(['status'=>0,'msg'=>'删除失败']));
            }
        }else{
            $this->error('无效的ID', '', '', 1);
        }
    }

    public function getCityList()
    {
        $province_id = input('post.province_id');
        $html = '';
        if($province_id){
            $city_list = Db::table('xm_region')->field('region_id,region_name')->where('parent_id',$province_id)->select();

            foreach($city_list as $key=>$value){
                $html .= "<option value='".$value['region_id']."'>".$value['region_name']."</option>";
            }
        }
        echo $html;
    }

    public function getCountryList()
    {
        $city_id = input('post.city_id');
        $html = '';
        if($city_id){
            $country_list = Db::table('xm_region')->field('region_id,region_name')->where('parent_id',$city_id)->select();
            foreach($country_list as $key=>$value){
                $html .= "<option value='".$value['region_id']."'>".$value['region_name']."</option>";
            }
        }
        echo $html;
    }

    public function log(){
        $page = input('get.page');
        $limit = input('get.limit');
        $map = [];
        if ($page && $limit) {
            if(input('get.name')){
                $name = input('get.name');
                $map['b.name'] =  ['like',"%$name%"];
            }
            if(input('get.user_phone')){
                $user_phone = input('get.user_phone');
                $map['c.user_phone'] =  security::encrypt($user_phone);
            }
            if(input('get.order_sn')){
                $order_sn = input('get.order_sn');
                $map['a.order_sn'] =  $order_sn;
            }
            if (input('get.start_time') && input('get.end_time')) {
                $start_time = input('get.start_time');
                $end_time = input('get.end_time');
                $map['a.create_time'] = ['between', [$start_time, $end_time]];
            }
            if(input('get.type')){
                $type = input('get.type');
                $map['a.type'] =  $type;
            }
            $start = ($page - 1) * $limit;
            $count = Db::name('business_log a')
                ->join('business b','a.business_id=b.id','LEFT')
                ->join('user c','a.uid=c.uid','LEFT')
                ->where($map)->count();
            $list = db('business_log a')->field('a.id,a.order_sn,a.first_money,a.percent_money,a.create_time,a.state,a.type,b.name,c.user_phone')
                ->join('business b','a.business_id=b.id','LEFT')
                ->join('user c','a.uid=c.uid','LEFT')
                ->where($map)->limit($start, $limit)->order('a.id desc')->select();
            foreach($list as $k=>$v){
                $list[$k]['user_phone'] = Security::decrypt($v['user_phone']);
                $list[$k]['first_money'] = "¥".sprintf('%.2f',$v['first_money']/100);
                $list[$k]['percent_money'] = "¥".sprintf('%.2f',$v['percent_money']/100);
                $list[$k]['state'] = $v['state']==1?'已支付':'待支付';
                if($v['type']==1){
                    $list[$k]['type'] = "首次下单";
                }elseif($v['type']==2){
                    $list[$k]['type'] = "首次登录";
                }else{
                    $list[$k]['type'] = "其它";
                }
            }
            return json([
                'code' => 0,
                'msg' => '',
                'limit' =>$limit,
                'count' => $count,
                'data' => $list
            ]);
        }
        return $this->fetch();
    }

    public function logExcel(){
        $type = input('get.type');
        $page = input('get.page') ?: 1;
        $limit = $type == 1 ? 1000 : input('get.limit');
        $start = ($page - 1) * $limit;
        $header = json_decode(input('get.headers'));
        $map = [];
        if(input('get.name')){
            $name = input('get.name');
            $map['b.name'] =  ['like',"%$name%"];
        }
        if(input('get.user_phone')){
            $user_phone = input('get.user_phone');
            $map['c.user_phone'] =  security::encrypt($user_phone);
        }
        if(input('get.order_sn')){
            $order_sn = input('get.order_sn');
            $map['a.order_sn'] =  $order_sn;
        }
        if (input('get.start_time') && input('get.end_time')) {
            $start_time = input('get.start_time');
            $end_time = input('get.end_time');
            $map['a.create_time'] = ['between', [$start_time, $end_time]];
        }
        if(input('get.type')){
            $type = input('get.type');
            $map['a.type'] =  $type;
        }
        $list = db('business_log a')->field('a.id,a.order_sn,a.first_money,a.percent_money,a.create_time,a.state,a.type,b.name,c.user_phone')
            ->join('business b','a.business_id=b.id','LEFT')
            ->join('user c','a.uid=c.uid','LEFT')
            ->where($map)->limit($start, $limit)->order('a.id desc')->select();
        if(empty($list)){
            return "<script>alert('暂无数据');parent.window.location.reload()</script>";
        }
        foreach($list as $k=>$v){
            $list[$k]['user_phone'] = Security::decrypt($v['user_phone']);
            $list[$k]['first_money'] = sprintf('%.2f',$v['first_money']/100);
            $list[$k]['percent_money'] = sprintf('%.2f',$v['percent_money']/100);
            $list[$k]['state'] = $v['state']==1?'已支付':'待支付';
            if($v['type']==1){
                $list[$k]['type'] = "首次下单";
            }elseif($v['type']==2){
                $list[$k]['type'] = "首次登录";
            }else{
                $list[$k]['type'] = "其它";
            }
        }
        foreach ($list as $key => $value) {
            foreach ($header as $k => $v) {
                $data[$key][$v] = $value[$k];
            }
        }
        Tools::excelExport('车队流水', $header, $data);
    }

}
